﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using ProjectGroep3.ws_Groep3;
using System.Windows.Forms;
using System.Web;
using ClassLibrary;
using System.Text.RegularExpressions;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;




namespace ProjectGroep3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Login : MetroWindow
    {
        private WebService ws = new WebService();
        private DataSet ds = new DataSet();
        private DataTable dt = new DataTable();
        private metroMessageDialog mmd = new metroMessageDialog();
        private bool controlPass = false,
            controlEmail = false,
            controlUsername = false,
            passEqualsConfPass = false,
            controlCombo = false;
        // constructors , methodes
        #region
        public Login()
        {
            InitializeComponent();

            startUp();
        }

        // Methode vult alle velden bij initialize
        private void startUp()
        {
            ds = ws.getCompany();
            dt = ds.Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                ComboBoxItem comboFill = new ComboBoxItem();
                comboFill.Content = row["Name"].ToString();
                comboFill.Tag = row["Id"].ToString();
                cmbCompany.Items.Add(comboFill);
            }
            txtLogin.Focus();
        }
        // Methode om Als gebruiker in te loggen
        private void loginUser(String name)
        {
            MainWindow form = new MainWindow(name);
            this.Close();
            form.Show();
        }
        // Methode om als Admin in te loggen
        private void loginAdmin()
        {
            AdminWindow formAdmin = new AdminWindow();
            formAdmin.Show();
            this.Close();
        }
        // foute login + clear velden melding 
        private void error_Wrong_Login()
        {
            mmd.generateDialog(this, "Error Login", "The username and/or password are invalid.");
            txtRegisterPass.Clear();
        }
        //Cleared alle velden en verbergt labels
        private void clearFields()
        {
            txtRegisterUserName.Clear();
            txtRegisterPass.Clear();
            txtRegisterConfPass.Clear();
            txtRegisterEmail.Clear();

        }
        private void clearImages()
        {
            imgConfPassFalse.Visibility = Visibility.Hidden;
            imgConfPassTrue.Visibility = Visibility.Hidden;
            imgPassFalse.Visibility = Visibility.Hidden;
            imgPassTrue.Visibility = Visibility.Hidden;
            imgUserFalse.Visibility = Visibility.Hidden;
            imgUserTrue.Visibility = Visibility.Hidden;
            imgEmailFalse.Visibility = Visibility.Hidden;
            imgEmailTrue.Visibility = Visibility.Hidden;

        }

        private void clearLabels()
        {
            lblInvalidEmail.Visibility = Visibility.Hidden;
            lblInvalidUsername.Visibility = Visibility.Hidden;
            lblInvalidPass.Visibility = Visibility.Hidden;
            lblUserNameDup.Visibility = Visibility.Hidden;
            lblEmailDup.Visibility = Visibility.Hidden;
        }
        #endregion
        // interactie met interface
        #region
        //Login knop
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Membership.ValidateUser(txtLogin.Text, TxtPass.Password))
                {
                    if (Roles.IsUserInRole(txtLogin.Text, "Administrators"))
                        loginAdmin();

                    else
                        loginUser(txtLogin.Text);
                }
                else
                    error_Wrong_Login();
            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "error", "More detail in logging file.");
            }

            //Easter Egg
            if (txtLogin.Text.Equals("Hodor"))
            {
                mmd.generateDialog(this, "Hodor", "Hodor!!");
            }

        }

        //Registreer knop
        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            clearImages();
            clearLabels();
            lblEmailDup.Visibility = Visibility.Hidden;
            lblUserNameDup.Visibility = Visibility.Hidden;
            MembershipCreateStatus createStatus;
            string passwordQuestion = "overload";
            string passwordAnswer = "overload";

            try
            {
                if (!(controlUsername == true))
                {
                    lblInvalidUsername.Visibility = Visibility.Visible;
                    imgUserFalse.Visibility = Visibility.Visible;
                    imgUserTrue.Visibility = Visibility.Hidden;
                }

                if (!(isValidEmail(txtRegisterEmail.Text) == true))
                {
                    lblInvalidEmail.Visibility = Visibility.Visible;
                    imgEmailFalse.Visibility = Visibility.Visible;
                    imgEmailTrue.Visibility = Visibility.Hidden;
                }

                if (validation(controlUsername, controlPass, passEqualsConfPass, controlEmail, controlCombo)==true)
                {
                    MembershipUser newUser = Membership.CreateUser(txtRegisterUserName.Text, txtRegisterPass.Password, txtRegisterEmail.Text, passwordQuestion, passwordAnswer, true, out createStatus);


                    if (newUser == null)
                    {
                        getErrorMessage(createStatus);
                    }
                    else
                    {
                        Roles.AddUserToRole(txtRegisterUserName.Text, "Users");
                        int CompId = Convert.ToInt32(((ComboBoxItem)this.cmbCompany.SelectedItem).Tag);
                        ws.setCompanyId(CompId, txtRegisterUserName.Text);
                        loginUser(txtRegisterUserName.Text);
                    }
                    
                }
                else
                {
                    txtRegisterPass.Clear();
                    txtRegisterConfPass.Clear();
                    clearImages();
                    mmd.generateDialog(this, "Error", "Please fill in all fields");
                }


            }
            catch (Exception ex)
            {
                Logging.Log(ex.Message + ex.StackTrace);
                mmd.generateDialog(this, "error", "more detail in logging file" + " " + controlUsername.ToString() + " " + controlEmail.ToString() + " " + controlPass.ToString() + " " + passEqualsConfPass.ToString());
            }
        }

        // Maakt velden op het register form leeg wanneer men naar het registratiescherm navigeert.
        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            clearImages();
            clearFields();
            clearLabels();
            txtRegisterUserName.Focus();
        }

        // Maakt velden leeg in de registratieform wanneer men terug naar het loginform gaat
        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            clearFields();
            clearImages();
            clearLabels();
        }
        #endregion
        //validatie
        #region
        //Controle op duplicates vooraleer men kan registreren
        public string getErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.Success:
                    Roles.AddUserToRole(txtRegisterUserName.Text, "Users");
                    int CompID = Convert.ToInt32(((ComboBoxItem)cmbCompany.SelectedItem).Tag);
                    ws.setCompanyId(CompID, txtRegisterUserName.Text);
                    loginUser(txtRegisterUserName.Text);
                    return "";
                case MembershipCreateStatus.DuplicateUserName:
                    lblUserNameDup.Visibility = Visibility.Visible;
                    lblInvalidUsername.Visibility = Visibility.Hidden;
                    imgUserFalse.Visibility = Visibility.Visible;
                    imgUserTrue.Visibility = Visibility.Hidden;
                    goto case MembershipCreateStatus.DuplicateEmail;
                case MembershipCreateStatus.DuplicateEmail:
                    lblEmailDup.Visibility = Visibility.Visible;
                    lblInvalidEmail.Visibility = Visibility.Hidden;
                    imgEmailFalse.Visibility = Visibility.Visible;
                    imgEmailTrue.Visibility = Visibility.Hidden;
                    return "";


                default:
                    return "Unknown error please contact your admin";

            }
        }
        //Password wordt vergeleken met ConfPassword
        private void txtRegisterConfPass_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (!(txtRegisterConfPass.Password.Equals(txtRegisterPass.Password)))
            {
                passEqualsConfPass = false;
                imgConfPassFalse.Visibility = Visibility.Visible;
                imgConfPassTrue.Visibility = Visibility.Hidden;

            }
            else
            {
                passEqualsConfPass = true;
                imgConfPassFalse.Visibility = Visibility.Hidden;
                imgConfPassTrue.Visibility = Visibility.Visible;
            }
        }

        //Usernamecontrole: mag geen whitespaces bevatten
        private void txtRegisterUserName_TextChanged(object sender, TextChangedEventArgs e)
        {

            if (!(isValidUsername(txtRegisterUserName.Text) == true))
            {
                controlUsername = false;
                imgUserFalse.Visibility = Visibility.Visible;
                imgUserTrue.Visibility = Visibility.Hidden;
            }
            else
            {
                controlUsername = true;
                imgUserFalse.Visibility = Visibility.Hidden;
                imgUserTrue.Visibility = Visibility.Visible;
            }
        }

        //Passwordcontrole: moet minstens 1 hoofdletter, 1 kleine letter, 1 cijfer, 1 speciaal teken bevatten en misnten 6 tekens lang zijn
        private void txtRegisterPass_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (!(isValidPass(txtRegisterPass.Password)==true))
            {
                controlPass = false;
                lblInvalidPass.Visibility = Visibility.Visible;
                imgPassFalse.Visibility = Visibility.Visible;
                imgPassTrue.Visibility = Visibility.Hidden;
            }
            else
            {
                controlPass = true;
                lblInvalidPass.Visibility = Visibility.Visible;
                imgPassFalse.Visibility = Visibility.Hidden;
                imgPassTrue.Visibility = Visibility.Visible;
            }
        }

        //Emailcontrole: moet in de vorm van test@test.com zijn
        private void txtRegisterEmail_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!(isValidEmail(txtRegisterEmail.Text) == true))
            {
                controlEmail = false;
                lblInvalidEmail.Visibility = Visibility.Visible; 
                lblEmailDup.Visibility = Visibility.Hidden;
                imgEmailFalse.Visibility = Visibility.Visible;
                imgEmailTrue.Visibility = Visibility.Hidden;
            }
            else
            {
                controlEmail = true;
                lblInvalidEmail.Visibility = Visibility.Visible;
                lblEmailDup.Visibility = Visibility.Hidden;
                imgEmailFalse.Visibility = Visibility.Hidden;
                imgEmailTrue.Visibility = Visibility.Visible;
            }
        }
        //Comboboxcontrole: moet geselecteerd worden
        private void cmbCompany_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbCompany.SelectedIndex >= 0)
            {
                controlCombo = true;
            }
            else controlCombo = false;
        }
        //E-mail validation
        public bool isValidEmail(string str)
        {
            return Regex.IsMatch(str, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*" + "@" + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
        }

        //Username validation
        public bool isValidUsername(string str)
        {
            return Regex.IsMatch(str, @"^(?=[a-zA-Z])[-\w.]{3,23}([a-zA-Z\d]|(?<![-.])_)$");
        }

        //PasswordValidation
        public bool isValidPass(string str)
        {
            return Regex.IsMatch(str, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{6,15}$");
        }

        //Validatie van de in te vullen velden in de registratie form. 
        public bool validation(bool user, bool pass, bool confPass, bool email, bool combo)
        {
            if (user == true && pass == true && confPass == true && email == true && combo == true)
                return true;
            else return false;
        }
        #endregion
    }
}
